<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单词默写大师</title>
    <style>
        :root {
            --primary-color: #FF9966;
            --primary-light: #FFDFD3;
            --primary-dark: #FF7733;
            --success-color: #4CAF50;
            --error-color: #F44336;
            --text-color: #333333;
            --bg-color: #FFFFFF;
            --canvas-bg: #FFFFFF;
            --header-bg: #FF9966;
            --container-bg: #FFFFFF;
            --button-bg: #FF9966;
            --button-text: #FFFFFF;
            --border-color: #DDDDDD;
            --shadow-color: rgba(0, 0, 0, 0.1);
        }

        .dark-mode {
            --primary-color: #333333;
            --primary-light: #444444;
            --primary-dark: #222222;
            --text-color: #F5F5F5;
            --bg-color: #121212;
            --canvas-bg: #2A2A2A;
            --header-bg: #333333;
            --container-bg: #1E1E1E;
            --button-bg: #454545;
            --button-text: #FFFFFF;
            --border-color: #444444;
            --shadow-color: rgba(0, 0, 0, 0.3);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            transition: all 0.3s ease;
        }

        .header {
            background-color: var(--header-bg);
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: white;
            transition: background-color 0.3s ease;
        }

        .window-controls {
            display: flex;
            gap: 10px;
        }

        .control {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }

        .control.red { background-color: #FF5F56; }
        .control.yellow { background-color: #FFBD2E; }
        .control.green { background-color: #27C93F; }

        .header-right {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logout-button, .profile-button {
            background-color: #FF9966;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 5px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .logout-button:hover, .profile-button:hover {
            background-color: #FF7733;
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
        }

        .dark-mode .logout-button, .dark-mode .profile-button {
            background-color: #454545;
        }

        .dark-mode .logout-button:hover, .dark-mode .profile-button:hover {
            background-color: #555555;
        }

        .dark-mode-toggle {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: white; /* Default light mode background */
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        /* Default SVG style (explicitly for light mode icon) */
        .dark-mode-toggle svg {
             stroke: #333; /* Dark stroke for moon icon */
             transition: stroke 0.3s ease;
        }

        .dark-mode-toggle:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        /* Adjust button background for dark mode */
        .dark-mode .dark-mode-toggle {
            background-color: #454545; /* Dark background for button in dark mode */
        }
        /* SVG style specifically for dark mode (sun icon) */
        .dark-mode .dark-mode-toggle svg {
            stroke: #FFF; /* White stroke for sun icon */
        }


        .container {
            width: 850px;
            height: 700px;
            margin: 0 auto;
            padding: 20px;
        }

        .login-container, .profile-container {
            background-color: var(--container-bg);
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 10px var(--shadow-color);
            text-align: center;
            max-width: 400px;
            margin: 50px auto;
        }

        .login-container h1, .profile-container h1 {
            margin-bottom: 20px;
            font-size: 28px;
            color: var(--text-color);
        }

        .login-container input, .profile-container input {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid var(--border-color);
            border-radius: 5px;
            font-size: 16px;
            color: var(--text-color);
            background-color: var(--bg-color);
        }

        .login-container .btn, .profile-container .btn {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .login-container .btn-primary, .profile-container .btn-primary {
            background-color: var(--button-bg);
            color: var(--button-text);
        }

        .login-container .btn-primary:hover, .profile-container .btn-primary:hover {
            background-color: var(--primary-dark);
        }

        .login-container .btn-outline, .profile-container .btn-outline {
            background-color: transparent;
            border: 1px solid var(--primary-color);
            color: var(--primary-color);
        }

        .login-container .btn-outline:hover, .profile-container .btn-outline:hover {
            background-color: var(--primary-light);
        }

        .profile-container .avatar-preview {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            margin: 10px auto;
            background-color: #eee;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
        }

        .profile-container .avatar-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .welcome-container {
            background-color: var(--primary-light);
            padding: 30px;
            border-radius: 8px;
            margin-bottom: 30px;
            text-align: center;
            color: var(--text-color);
            transition: background-color 0.3s ease;
        }

        .welcome-container h1 {
            margin-bottom: 20px;
            font-size: 28px;
        }

        .welcome-container p {
            margin-bottom: 15px;
            line-height: 1.6;
        }

        .wordlist-section {
            margin-top: 20px;
        }

        .wordlist-section h2 {
            margin-bottom: 20px;
            font-size: 24px;
        }

        .predefined-wordlists {
            display: flex;
            justify-content: space-between;
            gap: 10px;
            margin-bottom: 20px;
        }

        .predefined-wordlists .btn {
            flex: 1;
        }

        .custom-wordlist {
            background-color: var(--container-bg);
            border: 2px dashed var(--primary-color);
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 200px;
        }

        .custom-wordlist:hover {
            background-color: var(--primary-light);
        }

        .custom-wordlist .plus-icon {
            font-size: 48px;
            margin-bottom: 20px;
            color: var(--primary-color);
        }

        #fileInput, #avatarInput {
            display: none;
        }

        .practice-container {
            display: none;
            background-color: var(--container-bg);
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px var(--shadow-color);
            margin-top: 20px;
        }

        .practice-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .back-button {
            background: none;
            border: none;
            color: var(--primary-color);
            cursor: pointer;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .progress-indicator {
            background-color: var(--primary-light);
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 14px;
        }

        .word-display {
            background-color: var(--primary-light);
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }

        .word-display p {
            font-size: 14px;
            margin-bottom: 10px;
            color: var(--text-color);
        }

        .word-display h2 {
            font-size: 32px;
            font-weight: bold;
            color: var(--text-color);
        }

        .canvas-container {
            width: 100%;
            margin-bottom: 20px;
            position: relative;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            overflow: hidden;
            height: 200px;
        }

        #drawingCanvas {
            background-color: var(--canvas-bg);
            width: 100%;
            height: 100%;
            display: block;
            border-radius: 8px;
            cursor: crosshair;
        }

        .recognition-result {
            background-color: var(--primary-light);
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .recognition-result p {
            margin-bottom: 10px;
        }

        .result-input {
            width: 100%;
            padding: 8px;
            font-size: 18px;
            font-weight: bold;
            border: none;
            border-bottom: 2px solid var(--text-color);
            background: transparent;
            color: var(--text-color);
            outline: none;
            text-align: center;
        }

        .result-input::placeholder {
            color: #777;
            font-weight: normal;
        }

        .controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
        }

        .draw-controls {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .color-picker {
            display: flex;
            gap: 5px;
        }

        .color-option {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.2s ease;
        }

        .color-option.selected {
            transform: scale(1.2);
            border-color: var(--primary-dark);
        }

        .color-option.black { background-color: black; }
        .color-option.orange { background-color: #FF9966; }
        .color-option.blue { background-color: #3498db; }
        .color-option.green { background-color: #2ecc71; }
        .color-option.red { background-color: #e74c3c; }

        .eraser-tool {
            width: 32px;
            height: 32px;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13l4-4a2 2 0 0 0 0-2.8L14.8 1a2 2 0 0 0-2.8 0l-11 11a2 2 0 0 0 0 2.8L7.2 21a2 2 0 0 0 2.8 0L18 13z"></path><path d="M15 9l-5 5"></path></svg>');
            background-size: contain;
            cursor: pointer;
            opacity: 0.7;
            transition: opacity 0.2s ease;
        }

        .eraser-tool:hover, .eraser-tool.active {
            opacity: 1;
        }

        .shortcut-info {
            font-size: 12px;
            color: #777;
            text-align: right;
            margin-top: 5px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: var(--button-bg);
            color: var(--button-text);
        }

        .btn-primary:hover {
            background-color: var(--primary-dark);
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid var(--primary-color);
            color: var(--primary-color);
        }

        .btn-outline:hover {
            background-color: var(--primary-light);
        }

        .btn-danger {
            background-color: var(--error-color);
            color: white;
        }

        .btn-danger:hover {
            background-color: #D32F2F;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: var(--container-bg);
            border-radius: 8px;
            padding: 30px;
            width: 80%;
            max-width: 400px;
            text-align: center;
            position: relative;
            box-shadow: 0 5px 15px var(--shadow-color);
        }

        .modal h3 {
            margin-bottom: 20px;
            font-size: 24px;
        }

        .modal-icon {
            font-size: 48px;
            margin-bottom: 20px;
        }

        .success .modal-icon {
            color: var(--success-color);
        }

        .error .modal-icon {
            color: var(--error-color);
        }

        .modal-actions {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 10px;
        }

        .version-info {
            text-align: center;
            font-size: 12px;
            color: #777;
            margin-top: 30px;
        }

        @media (max-width: 600px) {
            .container {
                padding: 10px;
            }

            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="window-controls">
            <div class="control red"></div>
            <div class="control yellow"></div>
            <div class="control green"></div>
            <span style="margin-left: 10px;">单词默写大师</span>
        </div>
        <div class="header-right">
            <button class="profile-button" id="profileButton">个人中心</button>
            <button class="logout-button" id="logoutButton">退出登录</button>
            <div class="dark-mode-toggle" id="darkModeToggle">
                <!-- Icon is set by JavaScript -->
            </div>
        </div>
    </div>

    <!-- 登录页面 -->
    <div class="login-container" id="loginContainer">
        <h1>登录</h1>
        <input type="text" id="usernameInput" placeholder="用户名" required>
        <input type="password" id="passwordInput" placeholder="密码" required>
        <button class="btn btn-primary" id="loginButton">登录</button>
        <button class="btn btn-outline" id="registerButton">注册</button>
    </div>

    <!-- 个人中心页面 -->
    <div class="profile-container" id="profileContainer" style="display: none;">
        <h1>个人中心</h1>
        <p>用户名: <span id="profileUsername"></span></p>
        <div class="avatar-preview" id="avatarPreview">
            <img id="avatarImage" src="" alt="头像" style="display: none;">
            <span style="display: block;" id="avatarPlaceholder">无头像</span>
        </div>
        <input type="file" id="avatarInput" accept="image/*">
        <button class="btn btn-outline" id="uploadAvatarButton">上传头像</button>
        <input type="date" id="birthdayInput" placeholder="设置生日">
        <button class="btn btn-primary" id="saveProfileButton">保存</button>
        <p>已学习单词量: <span id="learnedWordsCount">0</span></p>
        <button class="btn btn-outline" id="backToWelcomeButton">返回</button>
    </div>

    <!-- 欢迎页面 -->
    <div class="container" id="welcomeContainer" style="display: none;">
        <div class="welcome-container">
            <h1>欢迎使用单词默写大师！</h1>
            <p>这是一款专为语言学习者设计的单词默写软件，支持手写输入和智能识别</p>
            <p>通过反复练习，有效提升你的单词记忆和拼写能力</p>
            <p>选择下方词库，开始你的默写之旅吧！</p>
        </div>

        <div class="wordlist-section">
            <h2>选择词库</h2>
            <div class="predefined-wordlists">
                <button class="btn btn-outline" id="ieltsButton">雅思词汇</button>
                <button class="btn btn-outline" id="toeflButton">托福词汇</button>
                <button class="btn btn-outline" id="cet4Button">四级词汇</button>
                <button class="btn btn-outline" id="cet6Button">六级词汇</button>
            </div>
            <div class="custom-wordlist" id="customWordlist">
                <div class="plus-icon">+</div>
                <h3>创建自定义词库</h3>
                <p>上传你自己的词库文件</p>
                <input type="file" id="fileInput" accept=".txt" />
            </div>
        </div>

        <p class="version-info">版本 1.0.0 | 词库总数: 1 | 单词总数: 0+</p>
    </div>

    <!-- 练习页面 -->
    <div class="container practice-container" id="practiceContainer" style="display: none;">
        <div class="practice-header">
            <button class="back-button" id="backButton">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M19 12H5M12 19l-7-7 7-7"></path>
                </svg>
                返回首页
            </button>
            <div class="practice-title" id="practiceTitle">自定义词库</div>
            <div class="progress-indicator" id="progressIndicator">1/30</div>
        </div>

        <div class="word-display">
            <p>请默写下面单词的英文</p>
            <h2 id="currentWord">苹果</h2>
        </div>

        <div class="canvas-container">
            <canvas id="drawingCanvas" width="600" height="200"></canvas>
        </div>

        <div class="recognition-result" id="recognitionResult">
            <p>识别结果：</p>
            <input type="text" class="result-input" id="resultInput">
        </div>

        <div class="controls">
            <div class="draw-controls">
                <div class="color-picker">
                    <div class="color-option black selected" data-color="black"></div>
                    <div class="color-option orange" data-color="#FF9966"></div>
                    <div class="color-option blue" data-color="#3498db"></div>
                    <div class="color-option green" data-color="#2ecc71"></div>
                    <div class="color-option red" data-color="#e74c3c"></div>
                </div>
                <div class="eraser-tool" id="eraserTool"></div>
                <div class="shortcut-info">按 Ctrl+Z 撤销 | 按空格键清空</div>
            </div>
            <div class="action-buttons">
                <button class="btn btn-outline" id="clearButton">清空画板</button>
                <button class="btn btn-primary" id="recognizeButton">识别</button>
                <button class="btn btn-primary" id="confirmButton">确认</button>
            </div>
        </div>
    </div>

    <!-- Success Modal -->
    <div class="modal success" id="successModal">
        <div class="modal-content">
            <div class="modal-icon">✓</div>
            <h3>正确！</h3>
            <p>单词 "<span id="correctWord"></span>" 拼写正确</p>
            <div class="modal-actions">
                <button class="btn btn-primary" id="nextWordButton">下一个</button>
            </div>
        </div>
    </div>

    <!-- Error Modal -->
    <div class="modal error" id="errorModal">
        <div class="modal-content">
            <div class="modal-icon">✗</div>
            <h3>错误！</h3>
            <p>正确拼写是: <span id="correctSpelling"></span></p>
            <div class="modal-actions">
                <button class="btn btn-outline" id="tryAgainButton">再试一次</button>
                <button class="btn btn-primary" id="nextWordErrorButton">下一个</button>
            </div>
        </div>
    </div>

    <script>
        // DOM Elements
        const loginContainer = document.getElementById('loginContainer');
        const usernameInput = document.getElementById('usernameInput');
        const passwordInput = document.getElementById('passwordInput');
        const loginButton = document.getElementById('loginButton');
        const registerButton = document.getElementById('registerButton');
        const welcomeContainer = document.getElementById('welcomeContainer');
        const practiceContainer = document.getElementById('practiceContainer');
        const customWordlist = document.getElementById('customWordlist');
        const fileInput = document.getElementById('fileInput');
        const backButton = document.getElementById('backButton');
        const practiceTitle = document.getElementById('practiceTitle');
        const progressIndicator = document.getElementById('progressIndicator');
        const currentWordElement = document.getElementById('currentWord');
        const drawingCanvas = document.getElementById('drawingCanvas');
        const ctx = drawingCanvas.getContext('2d');
        const resultInput = document.getElementById('resultInput');
        const clearButton = document.getElementById('clearButton');
        const recognizeButton = document.getElementById('recognizeButton');
        const confirmButton = document.getElementById('confirmButton');
        const successModal = document.getElementById('successModal');
        const errorModal = document.getElementById('errorModal');
        const correctWord = document.getElementById('correctWord');
        const correctSpelling = document.getElementById('correctSpelling');
        const nextWordButton = document.getElementById('nextWordButton');
        const tryAgainButton = document.getElementById('tryAgainButton');
        const nextWordErrorButton = document.getElementById('nextWordErrorButton');
        const darkModeToggle = document.getElementById('darkModeToggle');
        const eraserTool = document.getElementById('eraserTool');
        const colorOptions = document.querySelectorAll('.color-option');
        const logoutButton = document.getElementById('logoutButton');
        const profileButton = document.getElementById('profileButton');
        const profileContainer = document.getElementById('profileContainer');
        const profileUsername = document.getElementById('profileUsername');
        const avatarPreview = document.getElementById('avatarPreview');
        const avatarImage = document.getElementById('avatarImage');
        const avatarPlaceholder = document.getElementById('avatarPlaceholder');
        const avatarInput = document.getElementById('avatarInput');
        const uploadAvatarButton = document.getElementById('uploadAvatarButton');
        const birthdayInput = document.getElementById('birthdayInput');
        const saveProfileButton = document.getElementById('saveProfileButton');
        const learnedWordsCount = document.getElementById('learnedWordsCount');
        const backToWelcomeButton = document.getElementById('backToWelcomeButton');

        // App State
        let isDrawing = false;
        let currentColor = 'black';
        let isErasing = false;
        let lastX = 0;
        let lastY = 0;
        let drawHistory = [];
        let currentWordObject = null;
        let wordList = [];
        let completedWords = new Set();
        let totalWords = 0;
        let currentProgress = 0;
        // Define SVG icons as strings - Removed stroke="currentColor" relies solely on CSS
        const moonIconSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>`;
        const sunIconSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg>`;


        // Initialize canvas
        function initCanvas() {
            const container = drawingCanvas.parentElement;
            drawingCanvas.width = container.clientWidth;
            drawingCanvas.height = container.clientHeight;
            ctx.lineJoin = 'round';
            ctx.lineCap = 'round';
            ctx.lineWidth = 10;
            ctx.strokeStyle = currentColor;
            ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--canvas-bg');
            ctx.fillRect(0, 0, drawingCanvas.width, drawingCanvas.height);
            saveDrawState();
        }

        // Drawing functions
        function startDrawing(e) {
            isDrawing = true;
            [lastX, lastY] = getCoordinates(e);
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
        }

        function draw(e) {
            if (!isDrawing) return;
            const [x, y] = getCoordinates(e);
            if (isErasing) {
                const originalStyle = ctx.strokeStyle;
                const originalWidth = ctx.lineWidth;
                ctx.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue('--canvas-bg');
                ctx.lineWidth = 20;
                ctx.beginPath();
                ctx.moveTo(lastX, lastY);
                ctx.lineTo(x, y);
                ctx.stroke();
                ctx.strokeStyle = originalStyle;
                ctx.lineWidth = originalWidth;
            } else {
                ctx.beginPath();
                ctx.moveTo(lastX, lastY);
                ctx.lineTo(x, y);
                ctx.stroke();
            }
            [lastX, lastY] = [x, y];
        }

        function stopDrawing() {
            if (isDrawing) {
                isDrawing = false;
                saveDrawState();
            }
        }

        function getCoordinates(e) {
            let x, y;
            if (e.touches) {
                x = e.touches[0].clientX - drawingCanvas.getBoundingClientRect().left;
                y = e.touches[0].clientY - drawingCanvas.getBoundingClientRect().top;
            } else {
                x = e.offsetX;
                y = e.offsetY;
            }
            return [x, y];
        }

        function clearCanvas() {
            ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--canvas-bg');
            ctx.fillRect(0, 0, drawingCanvas.width, drawingCanvas.height);
            resultInput.value = "";
            saveDrawState();
        }

        function saveDrawState() {
            drawHistory.push(drawingCanvas.toDataURL());
            if (drawHistory.length > 20) drawHistory.shift();
            window.pywebview.api.add_history(drawingCanvas.toDataURL());
        }

        function undoDrawing() {
            if (drawHistory.length > 1) {
                drawHistory.pop();
                const lastState = drawHistory[drawHistory.length - 1];
                const img = new Image();
                img.onload = function() {
                    ctx.clearRect(0, 0, drawingCanvas.width, drawingCanvas.height);
                    ctx.drawImage(img, 0, 0);
                };
                img.src = lastState;
            } else {
                clearCanvas();
            }
        }

        // API functions
        function loadWordList(fileContent) {
            window.pywebview.api.load_custom_wordlist(fileContent)
                .then(response => {
                    if (response.success) {
                        totalWords = response.totalWords;
                        currentWordObject = response.currentWord;
                        currentProgress = 1;
                        practiceTitle.textContent = "自定义词库";
                        showPracticeScreen();
                        updateWordDisplay();
                    } else {
                        alert(response.message);
                    }
                });
        }

        function loadPredefinedWordlist(type) {
            window.pywebview.api.load_predefined_wordlist(type)
                .then(response => {
                    if (response.success) {
                        totalWords = response.totalWords;
                        currentWordObject = response.currentWord;
                        currentProgress = 1;
                        practiceTitle.textContent = response.wordlistName;
                        showPracticeScreen();
                        updateWordDisplay();
                    } else {
                        alert(response.message);
                    }
                });
        }

        function getNextWord() {
            window.pywebview.api.get_next_word()
                .then(response => {
                    if (response.completed) {
                        alert(response.message);
                        showWelcomeScreen();
                    } else {
                        currentWordObject = response.currentWord;
                        updateWordDisplay();
                        clearCanvas();
                    }
                });
        }

        function recognizeDrawing() {
            window.pywebview.api.save_drawing(drawingCanvas.toDataURL())
                .then(response => {
                    if (response.success) {
                        window.pywebview.api.recognize_drawing()
                            .then(result => {
                                if (result.success) {
                                    resultInput.value = result.recognized;
                                } else {
                                    alert("识别失败: " + result.message);
                                }
                            });
                    } else {
                        alert("保存图像失败: " + response.message);
                    }
                });
        }

        function checkAnswer(answer) {
            console.log("Calling check_answer with answer:", answer);
            if (!answer) {
                alert("请输入有效的答案");
                return;
            }

            window.pywebview.api.check_answer(answer)
                .then(result => {
                    console.log("check_answer result:", result);
                    if (!result) {
                        alert("答案检查失败：后端未返回有效结果");
                        console.error("check_answer returned null or undefined");
                        return;
                    }
                    if (!result.success) {
                        alert(result.message);
                        return;
                    }
                    correctWord.textContent = answer;
                    correctSpelling.textContent = result.correctAnswer;
                    if (result.correct) {
                        successModal.style.display = 'flex';
                    } else {
                        errorModal.style.display = 'flex';
                    }
                })
                .catch(error => {
                    console.error("Error in check_answer:", error);
                    alert("答案检查失败，请检查控制台日志");
                });
        }

        function loadUserProfile() {
            window.pywebview.api.get_user_info()
                .then(response => {
                    if (response.success) {
                        profileUsername.textContent = response.username;
                        if (response.avatar) {
                            avatarImage.src = `data:image/png;base64,${response.avatar}`;
                            avatarImage.style.display = 'block';
                            avatarPlaceholder.style.display = 'none';
                        } else {
                            avatarImage.style.display = 'none';
                            avatarPlaceholder.style.display = 'block';
                        }
                        birthdayInput.value = response.birthday || '';
                        learnedWordsCount.textContent = response.learned_words || 0;
                    } else {
                        alert(response.message);
                        showWelcomeScreen();
                    }
                });
        }

        // UI functions
        function showLoginScreen() {
            loginContainer.style.display = 'block';
            welcomeContainer.style.display = 'none';
            practiceContainer.style.display = 'none';
            profileContainer.style.display = 'none';
            logoutButton.style.display = 'none';
            profileButton.style.display = 'none';
        }

        function showWelcomeScreen() {
            loginContainer.style.display = 'none';
            welcomeContainer.style.display = 'block';
            practiceContainer.style.display = 'none';
            profileContainer.style.display = 'none';
            logoutButton.style.display = 'inline-block';
            profileButton.style.display = 'inline-block';
        }

        function showPracticeScreen() {
            loginContainer.style.display = 'none';
            welcomeContainer.style.display = 'none';
            practiceContainer.style.display = 'block';
            profileContainer.style.display = 'none';
            logoutButton.style.display = 'inline-block';
            profileButton.style.display = 'inline-block';
            initCanvas();
        }

        function showProfileScreen() {
            loginContainer.style.display = 'none';
            welcomeContainer.style.display = 'none';
            practiceContainer.style.display = 'none';
            profileContainer.style.display = 'block';
            logoutButton.style.display = 'inline-block';
            profileButton.style.display = 'inline-block';
            loadUserProfile();
        }

        function updateWordDisplay() {
            currentWordElement.textContent = currentWordObject.chinese;
            progressIndicator.textContent = currentWordObject.progress;
        }

        function setDarkModeIcon(isDark) {
             // Set the body class *first* so CSS rules apply correctly
             if (isDark) {
                 document.body.classList.add('dark-mode');
             } else {
                 document.body.classList.remove('dark-mode');
             }
             // Now set the icon, CSS will style it based on the body class
             darkModeToggle.innerHTML = isDark ? sunIconSVG : moonIconSVG;
        }

        function toggleDarkMode() {
            const isCurrentlyDark = document.body.classList.contains('dark-mode');
            // Toggle the state and update the icon
            setDarkModeIcon(!isCurrentlyDark);
            // Inform the backend
            window.pywebview.api.toggle_dark_mode();
        }

        // Setup color picker
        colorOptions.forEach(option => {
            option.addEventListener('click', () => {
                colorOptions.forEach(opt => opt.classList.remove('selected'));
                option.classList.add('selected');
                currentColor = option.dataset.color;
                ctx.strokeStyle = currentColor;
                isErasing = false;
                eraserTool.classList.remove('active');
                window.pywebview.api.set_draw_color(currentColor);
            });
        });

        // Event listeners
        loginButton.addEventListener('click', () => {
            const username = usernameInput.value.trim();
            const password = passwordInput.value.trim();
            if (!username || !password) {
                alert("请输入用户名和密码");
                return;
            }
            window.pywebview.api.login_user(username, password)
                .then(response => {
                    if (response.success) {
                        showWelcomeScreen();
                        window.pywebview.api.get_current_status()
                            .then(status => {
                                if (status.hasWordList) {
                                    currentWordObject = status.currentWord;
                                    showPracticeScreen();
                                    updateWordDisplay();
                                }
                                // Set initial dark mode state and icon correctly
                                setDarkModeIcon(status.darkMode);
                            });
                    } else {
                        alert(response.message);
                    }
                });
        });

        registerButton.addEventListener('click', () => {
            const username = usernameInput.value.trim();
            const password = passwordInput.value.trim();
            if (!username || !password) {
                alert("请输入用户名和密码");
                return;
            }
            window.pywebview.api.register_user(username, password)
                .then(response => {
                    alert(response.message);
                    if (response.success) {
                        usernameInput.value = '';
                        passwordInput.value = '';
                    }
                });
        });

        customWordlist.addEventListener('click', () => {
            fileInput.click();
        });

        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    loadWordList(event.target.result);
                };
                reader.readAsText(file);
            }
        });

        document.getElementById('ieltsButton').addEventListener('click', () => loadPredefinedWordlist('ielts'));
        document.getElementById('toeflButton').addEventListener('click', () => loadPredefinedWordlist('toefl'));
        document.getElementById('cet4Button').addEventListener('click', () => loadPredefinedWordlist('cet4'));
        document.getElementById('cet6Button').addEventListener('click', () => loadPredefinedWordlist('cet6'));

        backButton.addEventListener('click', showWelcomeScreen);

        drawingCanvas.addEventListener('mousedown', startDrawing);
        drawingCanvas.addEventListener('mousemove', draw);
        drawingCanvas.addEventListener('mouseup', stopDrawing);
        drawingCanvas.addEventListener('mouseout', stopDrawing);

        drawingCanvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            startDrawing(e);
        });
        drawingCanvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            draw(e);
        });
        drawingCanvas.addEventListener('touchend', stopDrawing);

        clearButton.addEventListener('click', clearCanvas);
        recognizeButton.addEventListener('click', recognizeDrawing);
        confirmButton.addEventListener('click', () => {
            const userAnswer = resultInput.value.trim();
            if (!userAnswer) {
                alert("请输入或识别你的答案！");
                return;
            }
            checkAnswer(userAnswer);
        });

        nextWordButton.addEventListener('click', () => {
            successModal.style.display = 'none';
            getNextWord();
        });

        tryAgainButton.addEventListener('click', () => {
            errorModal.style.display = 'none';
            clearCanvas();
        });

        nextWordErrorButton.addEventListener('click', () => {
            errorModal.style.display = 'none';
            getNextWord();
        });

        darkModeToggle.addEventListener('click', toggleDarkMode);

        eraserTool.addEventListener('click', () => {
            isErasing = !isErasing;
            if (isErasing) {
                eraserTool.classList.add('active');
            } else {
                eraserTool.classList.remove('active');
            }
        });

        logoutButton.addEventListener('click', () => {
            window.pywebview.api.logout_user()
                .then(response => {
                    if (response.success) {
                        alert(response.message);
                        showLoginScreen();
                        usernameInput.value = '';
                        passwordInput.value = '';
                        currentWordObject = null;
                        wordList = [];
                        completedWords = new Set();
                        totalWords = 0;
                        currentProgress = 0;
                        // Reset dark mode to default (light) and update icon
                        setDarkModeIcon(false);
                    } else {
                        alert(response.message);
                    }
                })
                .catch(error => {
                    console.error("Logout error:", error);
                    alert("退出登录失败，请检查控制台日志");
                });
        });

        profileButton.addEventListener('click', showProfileScreen);

        uploadAvatarButton.addEventListener('click', () => {
            avatarInput.click();
        });

        avatarInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const base64String = event.target.result.split(',')[1];
                    avatarImage.src = event.target.result;
                    avatarImage.style.display = 'block';
                    avatarPlaceholder.style.display = 'none';
                };
                reader.readAsDataURL(file);
            }
        });

        saveProfileButton.addEventListener('click', () => {
            const birthday = birthdayInput.value;
            // Check if avatarImage.src is a data URL before splitting
            const avatarData = avatarImage.src && avatarImage.src.startsWith('data:image') ? avatarImage.src.split(',')[1] : null;
            window.pywebview.api.update_user_profile(avatarData, birthday)
                .then(response => {
                    alert(response.message);
                    if (response.success) {
                        loadUserProfile();
                    }
                });
        });


        backToWelcomeButton.addEventListener('click', showWelcomeScreen);

        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'z') {
                e.preventDefault();
                undoDrawing();
            }
            if (e.key === ' ' && document.activeElement === document.body) {
                e.preventDefault();
                clearCanvas();
            }
        });

        window.addEventListener('load', () => {
            // Use a Promise to ensure pywebview is ready
            function checkPywebviewReady() {
                return new Promise((resolve) => {
                    if (window.pywebview && window.pywebview.api) {
                        resolve();
                    } else {
                        // Check again shortly
                        setTimeout(() => resolve(checkPywebviewReady()), 50);
                    }
                });
            }

            checkPywebviewReady().then(() => {
                 window.pywebview.api.get_current_status()
                    .then(status => {
                        if (status.isLoggedIn) {
                            logoutButton.style.display = 'inline-block';
                            profileButton.style.display = 'inline-block';
                            if (status.hasWordList) {
                                currentWordObject = status.currentWord;
                                showPracticeScreen();
                                updateWordDisplay();
                            } else {
                                showWelcomeScreen();
                            }
                            setDarkModeIcon(status.darkMode); // Set initial state and icon
                        } else {
                            showLoginScreen();
                            setDarkModeIcon(false); // Ensure light mode on login screen
                        }
                    })
                    .catch(err => {
                        console.error("Error getting initial status:", err);
                        // Fallback: Assume light mode if status fails
                        showLoginScreen(); // Or appropriate starting screen
                        setDarkModeIcon(false);
                    });
            });
        });


        window.addEventListener('resize', () => {
            if (practiceContainer.style.display !== 'none') {
                const imageData = drawingCanvas.toDataURL();
                initCanvas();
                const img = new Image();
                img.onload = function() {
                    ctx.drawImage(img, 0, 0);
                };
                img.src = imageData;
            }
        });
    </script>
</body>
</html>